<template>
  <div>
    <!-- <h1 class="title">数据存储设置</h1> -->
    <div
      class="setting-box dataStorageCon outreach-box"
      :class="treeStore.isShowStrategyDetail ? 'not-click' : ''"
      v-loading="loading"
    >
      <el-row>
        <el-col v-if="treeStore.osType == 'win'">
          <el-checkbox v-model="form.reserver.enable"></el-checkbox>
          <div class="text">
            数据保存<el-input
              v-model.number="form.reserver.time"
              @blur="
                if (form.reserver.time > 365) form.reserver.time = 365;
                if (form.reserver.time === '' || form.reserver.time < 1)
                  form.reserver.time = 1;
              "
            ></el-input
            >天【限定范围：1-365】
          </div>
        </el-col>
        <el-col v-if="treeStore.osType == 'linux'">
          <el-checkbox v-model="formLinux.reserver.enable"></el-checkbox>
          <div class="text">
            数据保存<el-input
              v-model.number="formLinux.reserver.time"
              @blur="
                if (formLinux.reserver.time > 365) formLinux.reserver.time = 365;
                if (formLinux.reserver.time === '' || formLinux.reserver.time < 1)
                  formLinux.reserver.time = 1;
              "
            ></el-input
            >天，自动清理最早一天的本程序数据
          </div>
        </el-col>
        <el-col v-if="treeStore.osType == 'win'">
          <el-checkbox v-model="form.diskCapacityPercentLimit.enable"></el-checkbox>
          <div class="text">
            程序安装所在磁盘使用空间超过<el-input
              v-model.number="form.diskCapacityPercentLimit.percent"
              @blur="
                if (form.diskCapacityPercentLimit.percent > 95)
                  form.diskCapacityPercentLimit.percent = 95;
                if (
                  form.diskCapacityPercentLimit.percent === '' ||
                  form.diskCapacityPercentLimit.percent < 60
                )
                  form.diskCapacityPercentLimit.percent = 60;
              "
            ></el-input
            >%时【限定范围：60-95】，提醒用户清理
            <i class="colorC2">（程序不自动清理）</i>
          </div>
        </el-col>
        <el-col v-if="treeStore.osType == 'win'">
          <el-checkbox v-model="form.diskCapacityLimit.enable"></el-checkbox>
          <div class="text">
            数据存储空间超过<el-input
              v-model.number="form.diskCapacityLimit.size"
              @blur="
                if (form.diskCapacityLimit.size > 2000)
                  form.diskCapacityLimit.size = 2000;
                if (
                  form.diskCapacityLimit.size === '' ||
                  form.diskCapacityLimit.size < 200
                )
                  form.diskCapacityLimit.size = 200;
              "
            ></el-input
            >MB时【限定范围：200-2000】，提醒用户清理
            <i class="colorC2">（程序不自动清理）</i>
          </div>
        </el-col>
        <el-col v-if="treeStore.osType == 'linux'">
          <el-checkbox v-model="formLinux.diskCapacityLimit.enable"></el-checkbox>
          <div class="text">
            数据存储空间超过<el-input
              v-model.number="formLinux.diskCapacityLimit.size"
              @blur="
                if (formLinux.diskCapacityLimit.size > 2000)
                  formLinux.diskCapacityLimit.size = 2000;
                if (
                  formLinux.diskCapacityLimit.size === '' ||
                  formLinux.diskCapacityLimit.size < 1
                )
                  formLinux.diskCapacityLimit.size = 1;
              "
            ></el-input
            >MB时，自动清理最早一天的本程序数据
          </div>
        </el-col>
        <el-col v-if="treeStore.osType == 'win'">
          <el-checkbox v-model="form.diskForceToDelete.enable"></el-checkbox>
          <div class="text">
            程序安装所在磁盘使用空间超过<el-input
              v-model.number="form.diskForceToDelete.percent"
              @blur="
                if (form.diskForceToDelete.percent > 99)
                  form.diskForceToDelete.percent = 99;
                if (
                  form.diskForceToDelete.percent === '' ||
                  form.diskForceToDelete.percent < 90
                )
                  form.diskForceToDelete.percent = 90;
              "
            ></el-input
            >%时【限定范围：90-99】
          </div>
        </el-col>
        <el-col v-if="treeStore.osType == 'linux'">
          <el-checkbox v-model="formLinux.diskForceToDelete.enable"></el-checkbox>
          <div class="text">
            程序安装所在磁盘使用空间超过<el-input
              v-model.number="formLinux.diskForceToDelete.percent"
              @blur="
                if (formLinux.diskForceToDelete.percent > 99)
                  formLinux.diskForceToDelete.percent = 99;
              "
            ></el-input
            >%时，自动清理最早一天的本程序数据
          </div>
        </el-col>
        <el-col>
          <el-button @click="confirm" class="el-button el-button--primary"
            >确定</el-button
          >
          <el-button @click="cancel">取消</el-button>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <div class="option">
        <el-button
          @click="backupDb"
          :icon="DocumentCopy"
          :disabled="!treeStore.treeDeviceId"
        >
          数据库备份
        </el-button>
        <el-button :icon="Coin" @click="recoveryDb" :disabled="!treeStore.treeDeviceId">
          数据库恢复
        </el-button>
      </div>
    </div>
    <chooseDbDialog
      :dialogAsync="dialogAsync"
      :name="dbName"
      :dbList="dbList"
      @closeDialog="dialogAsync = false"
      @recovery="recovery"
    ></chooseDbDialog>
  </div>
</template>

<script setup>
import chooseDbDialog from "./chooseDbDialog.vue";
import { ref, reactive, watch } from "vue";
import { DocumentCopy, Coin } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useTreeStore } from "~/utils/pinia/tree.js";
import {
  req_getDataStorage,
  req_setDataStorage,
  req_databaseBackup,
  req_getDbBackupList,
  req_databaseRevovery,
} from "~/utils/axios/index.js";
import { eventBus } from "~/utils/common/eventBus.js";
eventBus.on("getStrategyDetail", (detail) => {
  treeStore.openTreeFlag = false;
  if (treeStore.osType == "win") {
    form.value = JSON.parse(detail.data[0].storage_config);
  } else {
    formLinux.value = JSON.parse(detail.data[0].storage_config);
  }
});
const treeStore = useTreeStore();
treeStore.openTree();
const loading = ref(false);
const form = ref({
  reserver: {
    enable: false,
    time: null,
  },
  diskCapacityPercentLimit: {
    enable: false,
    percent: null,
  },
  diskCapacityLimit: {
    enable: false,
    size: null,
  },
  diskForceToDelete: {
    enable: false,
    percent: null,
  },
});
const formLinux = ref({
  diskCapacityLimit: {
    enable: true,
    size: null,
  },
  diskForceToDelete: {
    enable: true,
    percent: null,
  },
  reserver: {
    enable: true,
    time: null,
  },
});

watch(
  () => treeStore.treeDeviceId,
  () => {
    getDataStorage();
  }
);

const confirm = () => {
  if (!treeStore.treeDeviceId) return;
  let params = [
    {
      key: "storage_config",
      value:
        treeStore.osType == "win"
          ? JSON.stringify(form.value)
          : JSON.stringify(formLinux.value),
    },
  ];
  req_setDataStorage(treeStore.treeDeviceId, params)
    .then((res) => {
      res.data.succeed ? ElMessage.success("设置成功") : ElMessage.error("设置失败");
      getDataStorage();
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const cancel = () => {
  getDataStorage();
};
const backupDb = () => {
  loading.value = true;
  req_databaseBackup(treeStore.treeDeviceId)
    .then((res) => {
      loading.value = false;
      res.data.succeed ? ElMessage.success("备份成功") : ElMessage.error("备份失败");
    })
    .catch((err) => {
      loading.value = false;
    });
};
const dialogAsync = ref(false);
const dbName = ref("");
const dbList = ref([]);
const recoveryDb = () => {
  // 先获取数据库备份文件列表
  req_getDbBackupList(treeStore.treeDeviceId).then((res) => {
    if (res.data.data.length) {
      dbName.value = res.data.data[0].name;
      dbList.value = res.data.data;
      dialogAsync.value = true;
    } else {
      ElMessage.error("未检测到您的备份数据");
    }
  });
};
const recovery = (dbName) => {
  req_databaseRevovery(treeStore.treeDeviceId, { dbName: dbName }).then((res) => {
    res.data.succeed
      ? ElMessage.success(res.data.data)
      : ElMessage.error("数据库恢复失败");
    dialogAsync.value = false;
  });
};
const getDataStorage = async () => {
  if (!treeStore.treeDeviceId) return;
  loading.value = true;
  let params = ["storage_config"];
  try {
    const { data: res } = await req_getDataStorage(treeStore.treeDeviceId, params);
    loading.value = false;
    if (res.status) {
      if (res.osType == "win") {
        form.value = JSON.parse(res.data[0].storage_config);
      } else {
        formLinux.value = JSON.parse(res.data[0].storage_config);
      }
    }
  } catch (err) {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.dataStorageCon {
  background: #fff;
  padding: 0 20px 20px 20px;
}
.el-col,
.text {
  display: flex;
  align-items: center;
}
.el-col {
  margin: 20px 0;
}
.text {
  margin-left: 15px;
  :deep(.el-input) {
    width: 55px;
    height: 30px;
    margin: 0 10px;
  }
  :deep(.el-input__inner) {
    text-align: center;
  }
  .colorC2 {
    color: #afafaf;
    font-size: 14px;
  }
}
</style>
